package com.async_export_demo.export;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.async_export_demo.config.MyExportConfig;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.LinkedList;
import java.util.List;

public class DefaultDataProcessor implements DataProcessor {

    private static final DateTimeFormatter DTF = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");

    /**
     * 一个sheet页最多允许的数据条数
     */
    private static final long SHEET_MAX_SIZE = 200000;

    private String absoluteFileName;

    private String fileName;

    private long processedDataCount = 0;

    private ExcelWriter excelWriter;

    private MyExportConfig exportConfig;

    private final LinkedList<WriteSheet> writeSheets = new LinkedList<>();

    public DefaultDataProcessor(MyExportConfig exportConfig, Class<?> head) {
        this.exportConfig = exportConfig;
        this.absoluteFileName = getFileName(exportConfig);
        this.excelWriter = EasyExcel.write(absoluteFileName, head).build();
    }

    @Override
    public void processData(List<?> data) {
        WriteSheet writeSheet = getWriteSheet(data.size());
        this.excelWriter.write(data, writeSheet);
        processedDataCount += data.size();
    }

    @Override
    public void end() {
        this.excelWriter.close();
    }

    @Override
    public String getUrl() {
        // todo
        // 实际可能需要将本地文件推送到文件服务器，最终从文件服务器下载，此处直接返回本地地址
        return exportConfig.getDomain() + "/" + fileName;
    }

    private String getFileName(MyExportConfig exportConfig) {
        String fileName = LocalDateTime.now().format(DTF) + ".xlsx";
        this.fileName = fileName;
        return exportConfig.getRootPath() + "\\" + fileName;
    }

    private WriteSheet getWriteSheet(long currentProcessCount) {
        if (processedDataCount == 0) {
            WriteSheet writeSheet = EasyExcel.writerSheet(0, "模板").build();
            writeSheets.add(writeSheet);
        } else {
            long count = processedDataCount + currentProcessCount - SHEET_MAX_SIZE * (writeSheets.size() - 1);
            if (count > SHEET_MAX_SIZE) {
                writeSheets.add(EasyExcel.writerSheet(writeSheets.size(), "模板" + writeSheets.size()).build());
            }
        }
        return writeSheets.getLast();
    }

}
